<?PHP
class Page{
  public $id                 = -1;
  public $alias              = "";
  public $title              = "";
  public $ownerid            = -1;
  public $owner              = false;
  public $menu               = -1;
  public $advancedHtmlHeader = "";
  public $canonical          = "";
  public $inSitemap          = true;
  public $priority           = 0.5;
  private $changeFrequence   = 'monthly';
  private $meta              = null;
  private $editor            = null;
  public $editorText         = "";
  private $editorContent     = "";
  private static $current    = null;
  
  /**
   *
   * @param string $alias
   * @param boolean $loadforbreadcrumb 
   */
  function loadProperties($alias,$loadforbreadcrumb = false){
    if ($alias == "") {
      $alias = "home";
    }
    $this->alias = $alias;
    $row = DataBase::Current()->ReadRow("SELECT *,IFNULL(in_sitemap,1) in_sitemap_ifnull FROM {'dbprefix'}pages 
                           WHERE alias = '".$alias."'");
    $this->load($row,$loadforbreadcrumb);

  }
  
  /**
   *
   * @param int $id 
   */
  function loadPropertiesById($id){
    $id = DataBase::Current()->EscapeString($id);
    $row = DataBase::Current()->ReadRow("SELECT *,IFNULL(in_sitemap,1) in_sitemap_ifnull FROM {'dbprefix'}pages 
                           WHERE id = '".$id."'");
    $this->load($row);
  }
  
  /**
   *
   * @param mixed $data
   * @param boolean $loadforbreadcrumb 
   */
  function load($data,$loadforbreadcrumb = false){
    if($data){
      $this->id                 = $data->id;
      $this->title              = $data->title;
      $this->ownerid            = $data->owner;
      $this->menu               = $data->menu;
      $this->alias              = $data->alias;
      $this->editorContent      = $data->content;
      $this->loadforbeadrcumb   = $loadforbreadcrumb;
      $this->editorText         = $data->editor;
      $this->canonical          = $data->canonical;
      $this->advancedHtmlHeader = $data->advanced_html_header;
      $this->changeFrequence    = $data->change_frequence;
      $this->priority           = $data->priority;
      $this->inSitemap          = $data->in_sitemap_ifnull == 1;
      if(!isset(User::Current()->role) || !User::Current()->role->canAccess($this)){
        if(Settings::getValue("accessdenied") != $this->id){
          throw new AccessDeniedException("Access denied: ".$this->alias);
        }
      }
    }
    else{
      throw new FileNotFoundException("File Not Found: ".$this->alias);
    }
  }

  /**
   *
   * @return string
   */
  public function getMeta(){
    if($this->meta == null){
      $this->meta          = new Meta();
      $this->meta->pageid  = $this->id;
      $this->meta->load();
    }
    return $this->meta;
  }

  /**
   *
   * @return Editor
   */
  public function getEditor(){
    if($this->editor == null){
      $this->editor = new $this->editorText($this);
    }
    return $this->editor;
  }

  /**
   *
   * @param Editor $editor 
   */
  public function setEditor(Editor $editor){
    $this->editor = $editor;
  }

  function getContent(){
    EventManager::RaiseEvent("content_top",$this);
    $this->getEditor()->display();
    EventManager::RaiseEvent("content_bottom",$this);
  }

  /**
   *
   * @param boolean $loadforbreadcrumb
   * @return Page
   */
  function getOwner($loadforbreadcrumb = false){
    if(!$this->owner){
      $alias = DataBase::Current()->ReadField("SELECT alias FROM {'dbprefix'}pages 
                                          WHERE id = '".$this->ownerid."'");
      if($alias){
        $this->owner = new Page();
        $this->owner->loadProperties($alias,$loadforbreadcrumb);
      }
    }
    return $this->owner;
  }

  /**
   *
   * @return string
   */
  function getBreadcrumb(){
    if(Cache::contains("breadcrumb",$this->id)){
      $res = Cache::getData("breadcrumb",$this->id);
    }
    else{
      if(!$this->owner) $this->getOwner(true);
      if($this->owner){
        $res = $this->owner->getBreadcrumb();
      }
      $res[] = array($this->alias,$this->title);
      Cache::setData("breadcrumb",$this->id,$res);
    }
    return $res;
  }

  /**
   *
   * @return boolean
   */
  function save(){
    //Remove illigal charactors of the url
    $this->alias = str_replace("?","-",$this->alias);
    $this->alias = str_replace("&","-",$this->alias);
      
    $title              = DataBase::Current()->EscapeString($this->title);
    $alias              = DataBase::Current()->EscapeString($this->alias);
    $menu               = DataBase::Current()->EscapeString($this->menu);
    $id                 = DataBase::Current()->EscapeString($this->id);
    $ownerid            = DataBase::Current()->EscapeString($this->ownerid);
    $editorContent      = DataBase::Current()->EscapeString($this->editorContent);
    $advancedHtmlHeader = DataBase::Current()->EscapeString($this->advancedHtmlHeader);
    $canonical          = DataBase::Current()->EscapeString($this->canonical);
    $changeFrequence    = DataBase::Current()->EscapeString($this->changeFrequence);
    $priority           = DataBase::Current()->EscapeString($this->priority);
    if($this->inSitemap){
       $inSitemap = 1; 
    }
    else{
        $inSitemap = 0;
    }
    $res = DataBase::Current()->Execute("UPDATE {'dbprefix'}pages SET
                                    title    = '".$title."',
                                    alias    = '".$alias."',
                                    menu     = '".$menu."' ,
                                    content  = '".$editorContent."',
                                    owner  = '".$ownerid."',
                                    advanced_html_header  = '".$advancedHtmlHeader."',
                                    canonical  = '".$canonical."',
                                    update_timestamp = NOW(),
                                    priority = '".$priority."',
                                    change_frequence = '".$changeFrequence."',
                                    in_sitemap = ".$inSitemap."
                                    WHERE id = '".$id."'");
    $this->getMeta()->save();
    if($res){
      $args['title']   = $this->title;
      $args['alias']   = $this->alias;
      $args['menu']    = $this->menu;
      $args['id']      = $this->id;
      $args['ownerid'] = $this->ownerid;
      $args['content'] = $this->editorText;
      EventManager::RaiseEvent("page_saved",$args);
    }
    Cache::clear("breadcrumb");
    Cache::clear("page");
    return $res;
  }

  /**
   *
   * @param string $alias
   * @param string $editor
   * @param string $title
   * @return boolean
   */
  public static function create($alias,$editor,$title){
    $canonical = DataBase::Current()->EscapeString(UrlRewriting::GetUrlByAlias($alias));
    $alias     = DataBase::Current()->EscapeString($alias);
    $title     = DataBase::Current()->EscapeString($title);
    $editor    = DataBase::Current()->EscapeString($editor);
    $res = DataBase::Current()->Execute("INSERT INTO {'dbprefix'}pages (alias,editor, title, content, canonical) VALUES ('".$alias."','".$editor."','".$title."','<h1>".$title."</h1>','".$canonical."')");
    if($res){
      $res            = DataBase::Current()->InsertID();
      $args['id']     = $res;
      $args['editor'] = $editor;
      $args['alias']  = $alias;
      $admin = new Role();
      $admin->load(2);
      $admin->allowAccessByID($args['id']);
      EventManager::RaiseEvent("page_created",$args);
    }
	
	$args['id'] = DataBase::Current()->ReadField("SELECT id FROM {'dbprefix'}pages WHERE alias = '".$alias."'");
	
    Cache::clear("page");
    return $args['id'];
  }

  /**
   *
   * @return boolean
   */
  function delete(){
    $res = DataBase::Current()->Execute("DELETE FROM {'dbprefix'}pages WHERE alias = '".$this->alias."'");
    if($res){
      MenuEntry::DeleteByPage($this);
      $args['alias'] = $this->alias;
      EventManager::RaiseEvent("page_deleted",$args);
    }
    Cache::clear("breadcrumb");
    Cache::clear("page");
    return $res;
  }

  /**
   *
   * @return array
   */
  public static function getPagesTypes(){
    return DataBase::Current()->ReadRows("SELECT * FROM {'dbprefix'}pagetypes");
  }

  /**
   *
   * @param string $separator
   * @param string $class
   * @param string $idpraefix 
   */
  function displayBreadcrumb($separator,$class,$idpraefix){
    $this->getEditor()->displayBreadcrumb($separator,$class,$idpraefix);
  }

  /**
   *
   * @param string $dir
   * @param int $limit_start Limit Start
   * @param int $limit_size Result Count
   * @return array
   */
  static function getPagesByDir($dir,$limit_size = -1,$limit_start = -1){
    $dir = DataBase::Current()->EscapeString($dir);
    if(substr($dir,0,1) == "/"){
      $dir = substr($dir,1);
    }
    
    $limit = "";
    
    if(is_numeric($limit_start) && is_numeric($limit_size)){
        
        if($limit_size > -1 && $limit_start == -1){
            $limit = " LIMIT ".$limit_size;
        }
        else if($limit_start > -1){
            $limit = " LIMIT ".$limit_start.",".$limit_size;
        }
    }
    
    
    return DataBase::Current()->ReadRows("SELECT * FROM {'dbprefix'}pages 
                           WHERE alias LIKE '".$dir."%'"." ORDER BY title,alias".$limit);
    
  }
  
  static function countPagesByDir($dir){
    $dir = DataBase::Current()->EscapeString($dir);
    if(substr($dir,0,1) == "/"){
      $dir = substr($dir,1);
    }
      
    return DataBase::Current()->ReadField("SELECT COUNT(*) FROM {'dbprefix'}pages 
                           WHERE alias LIKE '".$dir."%'");
  }
  
  /**
   *
   * @return array 
   */
  public static function GetAllPages(){
      $res = array();
      
      $rows = DataBase::Current()->ReadRows("SELECT * FROM {'dbprefix'}pages");
      foreach($rows as $row){
          try{
              $obj = new Page();
              $obj->load($row);
              $res[] = $obj;
          }
          catch(AccessDeniedException $ex){
          }
      }
      
      return $res;
  }

  /**
   *
   * @return string
   */
  public function getEditorContent(){
    return $this->editorContent;
  }

  /**
   *
   * @param string $content
   */
  public function setEditorContent($content){
    $this->editorContent = $content;
  }

  /**
   *
   * @return string 
   */
  public function getDir(){
    $res = "";
    if(strpos($this->alias,"/") > -1){
      $parts = explode('/',$this->alias);
      for($i = 0;$i<sizeOf($parts)-1;$i++){
        $res .= $parts[$i]."/";
      }
    }
    return $res;
  }

  /**
   *
   * @return string
   */
  public function getLocalAlias(){
    $res = "";
    $parts = explode('/',$this->alias);
    $res = $parts[sizeOf($parts)-1];
    return $res;
  }
  
  /**
   *
   * @param string $parameter
   * @return string
   */
  public function GetUrl($parameter = ""){
	return UrlRewriting::GetUrlByPage($this,$parameter);
  }
  
  /**
   * @return Page the open page
   */
  public static function Current(){
    if(self::$current == null){
        try{
          self::$current = new Page();
          self::$current->loadProperties(DataBase::Current()->EscapeString(sys::getAlias()));
        }
        catch(ContentLionException $ex){
          self::$current = $ex->getErrorPage();
        }
    }
    return self::$current;
  }
  
  public function GetHeader(){
    $res = "";
    $res .= $this->getEditor()->getHeader();
    if($this->canonical != ""){
        $res .= "<link rel=\"canonical\" href=\"".$this->canonical."\" />";
    }
    $res .= $this->advancedHtmlHeader;
    return  $res;
  }
  
  /**
   * Sets, how often the article is changing
   * @param string $frequence (always, horuly, daily, monthly, yealry or never)
   */
  public function SetChangeFrequence($frequence){
      $frequence = strtolower($frequence);
      if(in_array($frequence,array("always","hourly","daily","monthly","yearly","never"))){
          $this->changeFrequence = $frequence;
      }
  }
  
  /**
   *
   * @return string $frequence (always, horuly, daily, monthly, yealry or never)
   */
  public function GetChangeFrequence(){
      return $this->changeFrequence;
  }
  
  /**
   * Executes the Http-Header Commands
   */
  public function ExecuteHttpHeader(){
      $editor = $this->getEditor();
      if(isset($editor)){
        $editor->ExecuteHttpHeader();
      }
  }
}

?>
